//  <(((*> <(((*> ><(((*> ><(((*> ><(((*> ><(((*> ><(((*> ><(((*> ><(((*>
//
//          EXIF ReName
//          Copyright (C) 2007 - 2021 Ingemar Ceicer
//          https://gitlab.com/posktomten/exifrename2
//          ic_0002 (at) ceicer (dot) com
//
//   This program is free software: you can redistribute it and/or modify
//   it under the terms of the GNU General Public License version 3
//   as published by the Free Software Foundation.
//
//   This program is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU General Public License for more details.
//
// <(((*> <(((*> ><(((*> ><(((*> ><(((*> ><(((*> ><(((*> ><(((*> ><(((*>
#include "tabwidget.h"
#include "mainwindow.h"
#include "ui_tabwidget.h"
#ifdef Q_OS_LINUX
#include "update.h"
#include "updatedialog.h"
#include "checkupdate.h"
#endif

#include <QApplication>
TabWidget::TabWidget(QWidget *parent)
    : QTabWidget(parent), ui(new Ui::TabWidget)
{
    firstRun();
    this->setAttribute(Qt::WA_DeleteOnClose, true);
    this->setFixedSize(725, 630);
    ui->setupUi(this);
#ifdef Q_OS_WIN
#ifndef portable
    ui->checkChortcutApplicationsLocation->setVisible(false);
    ui->frame_15->setFixedHeight(51);
    ui->frame_17->move(10, 189);
    ui->frame_18->move(485, 189); // Preview language
    ui->frame_19->move(10, 283);
#endif
#ifdef portable
    ui->frame_17->move(10, 225);
    ui->frame_18->move(485, 225);  // Preview language
    ui->frame_19->move(10, 319);
#endif
#endif
#ifndef Q_OS_LINUX
    ui->frame_14->setVisible(false);
    ui->frame_15->move(10, 130);
#endif
    this->setWindowTitle(DISPLAY_NAME " " VERSION);
    readPlaceonscreen();
    testTranslation();
    QColor c(RED, GREEN, BLUE);
    QPalette p = ui->textBrowser->palette(); // define pallete for textEdit..
    p.setColor(QPalette::Base, c); // set color "Red" for textedit base
    ui->textBrowser->setPalette(p); // change textedit palette
    Info *info = new Info;
    QString about = info->getSystem();
    ui->textBrowser->setText(about);
    ui->textBrowser->setOpenExternalLinks(true);
    QString fontPathRegular = ":/fonts/Ubuntu-R.ttf";
    int fontidRegular = QFontDatabase::addApplicationFont(fontPathRegular);
    QString regular = QFontDatabase::applicationFontFamilies(fontidRegular).at(0);
    QFont fregular(regular, FONTSIZE, QFont::Normal);
    QString fontPathMono = ":/fonts/UbuntuMono-R.ttf";
    int fontidMono = QFontDatabase::addApplicationFont(fontPathMono);
    QString mono = QFontDatabase::applicationFontFamilies(fontidMono).at(0);
    fmono = new QFont(mono, FONTSIZE + 1, QFont::Normal);
    setStartConfig();
    this->setFont(fregular);
    ui->lblFolder->setFont(*fmono);
    ui->lblCurrentDateTime->setFont(*fmono);
    ui->lblCopyLocation->setFont(*fmono);
    /*     connect      */
    /* FILE NAME PATTERN */
    /* Folder for Years */
    connect(ui->checkYears, &QCheckBox::clicked, [this]() {
        setEndConfig();
        setStartConfig();
    });
    /* Folder for file extension */
    connect(ui->checkExtension, &QCheckBox::clicked, [this]() {
        setEndConfig();
        setStartConfig();
    });
    /* Close */
    connect(ui->pbClose, &QPushButton::clicked, [this]() {
        close();
    });
    /* Save text */
    connect(ui->pbSave, &QPushButton::clicked, [this]() {
        if(ui->cmbInsert->currentText() != "") {
            QStringList insert;

            for(int i = 0; i < ui->cmbInsert->count(); i++) {
                insert << ui->cmbInsert->itemText(i);
            }

            if(!insert.contains(ui->cmbInsert->currentText())) {
                ui->cmbInsert->addItem(ui->cmbInsert->currentText());
            }
        }
    });
    connect(ui->pbRemove, &QPushButton::clicked, [this]() {
        ui->cmbInsert->removeItem(ui->cmbInsert->currentIndex());
    });
    /* Only time in file name */
    connect(ui->checkOnlyTime, &QCheckBox::clicked, [this]() {
        if(ui->checkOnlyTime->isChecked()) {
            ui->cmbDateTime->setDisabled(true);
        }

        setEndConfig();
        setStartConfig();
    });
    /* radio extension */
    connect(ui->radioCapital, &QRadioButton::toggled, [this]() {
        QString tmp = ui->lblCurrentDateTime->text();
        int langd = tmp.size();
        int dot = tmp.lastIndexOf('.');
        tmp = tmp.remove(dot, langd - dot);
        tmp = tmp + tr(".EXTENSION");
        ui->lblCurrentDateTime->setText(tmp);
    });
    connect(ui->radioLowercase, &QRadioButton::toggled, [this]() {
        QString tmp = ui->lblCurrentDateTime->text();
        int langd = tmp.size();
        int dot = tmp.lastIndexOf('.');
        tmp = tmp.remove(dot, langd - dot);
        tmp = tmp + tr(".extension");
        ui->lblCurrentDateTime->setText(tmp);
    });
    connect(ui->radioKeep, &QRadioButton::toggled, [this]() {
        QString tmp = ui->lblCurrentDateTime->text();
        int langd = tmp.size();
        int dot = tmp.lastIndexOf('.');
        tmp = tmp.remove(dot, langd - dot);
        tmp = tmp + tr(".extension");
        ui->lblCurrentDateTime->setText(tmp);
    });
    /* Folder name */
    connect(
        ui->cmbFolderName, QOverload<int>::of(&QComboBox::currentIndexChanged),
    [this](int index) {
        QString foldernamepattern = ui->lblFolder->text();
        int hitta = foldernamepattern.indexOf(QDir::toNativeSeparators("/"));

        if(hitta > 0) {
            foldernamepattern.remove(0, 5);
        }

        switch(index) {
            case 0:
                foldernamepattern.replace(4, 1, ' ');
                foldernamepattern.replace(7, 1, ' ');
                break;

            case 1:
                foldernamepattern.replace(4, 1, '-');
                foldernamepattern.replace(7, 1, '-');
                break;

            case 2:
                foldernamepattern.replace(4, 1, '_');
                foldernamepattern.replace(7, 1, '_');
                break;
        }

        /* Folder for Years */
        if(ui->checkYears->isChecked()) {
            QString years = foldernamepattern;
            years = years.left(4);
            years = years + QDir::toNativeSeparators("/");
            foldernamepattern = years + foldernamepattern;
            ui->lblFolder->setText(foldernamepattern);
        } else {
            ui->lblFolder->setText(foldernamepattern);
        }
    });
    /* datetime */
    connect(ui->cmbDateTime, QOverload<int>::of(&QComboBox::currentIndexChanged),
    [this](int index) {
        QString filenamepattern = ui->lblCurrentDateTime->text();

        switch(index) {
            case 0:
                filenamepattern.replace(10, 1, ' ');
                break;

            case 1:
                filenamepattern.replace(10, 1, '-');
                break;

            case 2:
                filenamepattern.replace(10, 1, '_');
                break;
        }

        ui->lblCurrentDateTime->setText(filenamepattern);
    });
    /* filename pattern */
    connect(ui->cmbFileName, QOverload<int>::of(&QComboBox::currentIndexChanged),
    [this](int index) {
        QString filenamepattern = ui->lblCurrentDateTime->text();

        if(!ui->checkOnlyTime->isChecked()) {
            switch(index) {
                case 0:
                    filenamepattern.replace(4, 1, ' ');
                    filenamepattern.replace(7, 1, ' ');
                    filenamepattern.replace(13, 1, ' ');
                    filenamepattern.replace(16, 1, ' ');
                    break;

                case 1:
                    filenamepattern.replace(4, 1, '-');
                    filenamepattern.replace(7, 1, '-');
                    filenamepattern.replace(13, 1, '-');
                    filenamepattern.replace(16, 1, '-');
                    break;

                case 2:
                    filenamepattern.replace(4, 1, '_');
                    filenamepattern.replace(7, 1, '_');
                    filenamepattern.replace(13, 1, '_');
                    filenamepattern.replace(16, 1, '_');
                    break;
            }
        } else {
            // yyyy-MM-dd_hh-mm-ss
            switch(index) {
                case 0:
                    filenamepattern.replace(2, 1, ' ');
                    filenamepattern.replace(5, 1, ' ');
                    break;

                case 1:
                    filenamepattern.replace(2, 1, '-');
                    filenamepattern.replace(5, 1, '-');
                    break;

                case 2:
                    filenamepattern.replace(2, 1, '_');
                    filenamepattern.replace(5, 1, '_');
                    break;
            }
        }

        ui->lblCurrentDateTime->setText(filenamepattern);
    });
    /* END FILE NAME PATTERN */
    /* EXTENSIONS */
    connect(ui->pbCloseExtension, &QPushButton::clicked, [this]() {
        close();
    });
    // Filter open
    connect(ui->pbDefaultExtension, &QPushButton::clicked, this, &TabWidget::defaultExtensions);
    connect(ui->pbNewExtension, &QPushButton::clicked, this, &TabWidget::newExtensions);
    connect(ui->pbRemoveExtension, &QPushButton::clicked, this, &TabWidget::removeExtensions);
    // Filter rekursive
    connect(ui->pbDefaultExtension_2, &QPushButton::clicked, this, &TabWidget::defaultExtensions2);
    connect(ui->pbNewExtension_2, &QPushButton::clicked, this, &TabWidget::newExtensions2);
    connect(ui->pbRemoveExtension_2, &QPushButton::clicked, this, &TabWidget::removeExtensions2);
    /* END EXTENSIONS */
    /*  OPEN COPY TO  */
    connect(ui->pbCloseOpenCopy, &QPushButton::clicked, [this]() {
        close();
    });
    connect(ui->pbSetLocation, &QPushButton::clicked, this, &TabWidget::selectCopyTo);
    QDir dir(QDir::homePath());
    QString home = QDir::toNativeSeparators(dir.path());
    ui->radioHome->setText(tr("Always open") + " " + home);
    /* END OPEN COPY TO */
    /*   MISCELLANEOUS  */
    connect(ui->pbCloseMiscellaneous, &QPushButton::clicked, [this]() {
        close();
    });
    connect(ui->checkChortcutDesktopLocation, &QCheckBox::stateChanged, [this](int state) {
        chortcutdesktop(state);
    });
    connect(ui->checkChortcutApplicationsLocation, &QCheckBox::stateChanged, [this](int state) {
        chortcutapplications(state);
    });
#ifdef Q_OS_LINUX
    connect(ui->pbForceUpdate, &QPushButton::clicked, [this]() {
        // QDialog class
        UpdateDialog *ud = new UpdateDialog;
        ud->show();
        // QObject class
        Update *up = new Update;
        // Contact is established, the slot "isUpdated" listens for a signal from
        // the update class "isUpdated"
        connect(up, &Update::isUpdated, this, &TabWidget::isUpdated);
        // Pointer is sent so that "ud" can be deleted
        up->doUpdate(ARG1, ARG2, DISPLAY_NAME, ud);
    });
#endif
    /*  END MISCELLANEOUS  */
    /* LICENSE */
    connect(ui->pbCloseLicense, &QPushButton::clicked, [this]() {
        close();
    });
    QFile file(":/txt/LICENSE");

    if(file.exists()) {
        file.open(QIODevice::ReadOnly);
        QTextStream stream(&file);
        stream.setCodec("UTF-8");
        QString content = stream.readAll();
        file.close();
        ui->textBrowserLicense->setText(content);
    }

    /* END LICENSE */
    /* ABOUT */
    /* Close About */
    connect(ui->pbCloseAbout, &QPushButton::clicked, [this]() {
        close();
    });
    /* END ABOUT */
    /*  SLUT connect   */
}

QChar TabWidget::indexToChar(int index)
{
    switch(index) {
        case 0:
            return ' ';
            break;

        case 1:
            return '-';
            break;

        case 2:
            return '_';
            break;
    }

    return '-';
}
void TabWidget::isUpdated(bool b)
{
    if(b) {
//        QMessageBox::information(this, DISPLAY_NAME " " VERSION,
//                                 tr("Please close EXIF ReName and start using the updated program."));
#ifdef Q_OS_LINUX
        emit mainwindowclosing();
#endif
        close();
    } else {
        QMessageBox::critical(this, DISPLAY_NAME " " VERSION,
                              tr("An unexpected error occurred during the forced update."));
    }
}
TabWidget::~TabWidget()
{
    writePlaceonscreen();
    setEndConfig();
    emit tabwidgetclosing();
    delete ui;
}
